package com.ruiyin.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import net.sf.json.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.ruiyin.bean.Weixinparameters;
import com.ruiyin.interceptor.BaseInterceptor;
import com.ruiyin.service.WeixinService;
import com.ruiyin.util.EscapeUnescape;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;

/**
 * 
* 类名称：WeixinController.java
* 类描述： 微信公共平台开发 
* @author FH
* 作者单位： 
* 联系方式：
* 创建时间：2014年7月10日
* @version 1.0
 */
@Before(BaseInterceptor.class)
public class WeixinController extends Controller{
    public static String appID=null;
    public static String appSecret=null;
    
		public void toauth(){
			String ID =getPara("ID");
			
			System.out.println("in to auth");
			
			Weixinparameters weixin = getModel(Weixinparameters.class);
			weixin.setId(ID);
			WeixinService weixinS = new WeixinService();
			
			List<Weixinparameters> list = weixinS.paginate(ID);
				if(list.size()>0){
				weixin = list.get(0);
				appID=weixin.getAppid();
				appSecret = weixin.getAppsercret();
				setAttr("appid", weixin.getAppid());
				renderJsp("index.jsp");
			}else{
				renderJsp("error.jsp");
			}
		}
	
	 public void index(
			 ) throws Exception{ 
		
	    String code =getPara("code");
	    if(code == "" || code ==null){
	    	 String requestUrl= "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appID+"&redirect_uri=http://wvphqvga8r.proxy.qqbrowser.cc/wxmarket/auth&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	    	 httpRequst(requestUrl, "GET", null);
	    }else{
		    code = URLDecoder.decode(code,"UTF-8"); 
			 //011GkjbI00bJ252LAKaI0XhlbI0Gkjbk
			 String requestUrl= "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appID+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
			
			 JSONObject jsonObject = httpRequst(requestUrl, "GET", null);
			 
			 String urls="https://api.weixin.qq.com/sns/userinfo?access_token="+jsonObject.get("access_token")+"&openid="+jsonObject.get("openid")+"&lang=zh_CN";
			 JSONObject userInfo = httpRequst(urls, "GET", null);
			 setAttr("userInfo", EscapeUnescape.escape(userInfo.toString()));
			 renderJsp("auth.jsp");
	    }
	 }
	 
	  public String sendGet(String urlNameString) {
	        String result = "";
	        BufferedReader in = null;
	        try {
	            
	            URL realUrl = new URL(urlNameString);
	            // 打开和URL之间的连接
	            URLConnection connection = realUrl.openConnection();
	            // 设置通用的请求属性
	            connection.setRequestProperty("accept", "*/*");
	            connection.setRequestProperty("connection", "Keep-Alive");
	            connection.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            // 建立实际的连接
	            connection.connect();
	            // 获取所有响应头字段
	            Map<String, List<String>> map = connection.getHeaderFields();
	            // 遍历所有的响应头字段
	            for (String key : map.keySet()) {
	                System.out.println(key + "--->" + map.get(key));
	            }
	            // 定义 BufferedReader输入流来读取URL的响应
	            in = new BufferedReader(new InputStreamReader(
	                    connection.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("发送GET请求出现异常！" + e);
	            e.printStackTrace();
	        }
	        // 使用finally块来关闭输入流
	        finally {
	            try {
	                if (in != null) {
	                    in.close();
	                }
	            } catch (Exception e2) {
	                e2.printStackTrace();
	            }
	        }
	        return result;
	    }
	 
	 public JSONObject httpRequst(String requestUrl,String requetMethod,String outputStr){
			JSONObject jsonobject=null;
			StringBuffer buffer=new StringBuffer();
			try
			{
				//创建SSLContext对象，并使用我们指定的新人管理器初始化
				TrustManager[] tm={new MyX509TrustManager()};
				SSLContext sslcontext=SSLContext.getInstance("SSL","SunJSSE");
				sslcontext.init(null, tm, new java.security.SecureRandom());
				//从上述SSLContext对象中得到SSLSocktFactory对象
				SSLSocketFactory ssf=sslcontext.getSocketFactory();
				
				URL url=new URL(requestUrl);
				HttpsURLConnection httpUrlConn=(HttpsURLConnection)url.openConnection();
				httpUrlConn.setSSLSocketFactory(ssf);
				
				httpUrlConn.setDoOutput(true);
				httpUrlConn.setDoInput(true);
				httpUrlConn.setUseCaches(false);
				//设置请求方式（GET/POST）
				httpUrlConn.setRequestMethod(requetMethod);
				
				if("GET".equalsIgnoreCase(requetMethod))
					httpUrlConn.connect();
				
				//当有数据需要提交时
				if(null!=outputStr)
				{
				OutputStream outputStream=httpUrlConn.getOutputStream();
				//注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
				}
				
				//将返回的输入流转换成字符串
				InputStream inputStream=httpUrlConn.getInputStream();
				InputStreamReader inputStreamReader=new InputStreamReader(inputStream,"utf-8");
				BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
				
				
				String str=null;
				while((str = bufferedReader.readLine()) !=null)
				{ 
					buffer.append(str);
				}
				bufferedReader.close();
				inputStreamReader.close();
				//释放资源
				inputStream.close();
				inputStream=null;
				httpUrlConn.disconnect();
				jsonobject=JSONObject.fromObject(buffer.toString());
			}
			catch (ConnectException ce) {
				// TODO: handle exception
				ce.printStackTrace();
			}
			catch (Exception e) { 
				e.printStackTrace();
			}
			return jsonobject;
		}
		//================================================获取access_token==============================================================
}
	 class MyX509TrustManager implements X509TrustManager
	 {

	 	public void checkClientTrusted(X509Certificate[] chain, String authType)
	 			throws CertificateException {
	 		// TODO Auto-generated method stub
	 		
	 	}

	 	public void checkServerTrusted(X509Certificate[] chain, String authType)
	 			throws CertificateException {
	 		// TODO Auto-generated method stub
	 		
	 	}

	 	public X509Certificate[] getAcceptedIssuers() {
	 		// TODO Auto-generated method stub
	 		return null;
	 	}
	 

}
